package download;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import customization.Constants;

public class Download
{
	
	public String dir=null;
	public String fileInputs=null;
	public StubForWebServiceMethod ws=null;
	
	public Download(StubForWebServiceMethod ws, String fileInputs, String dirResults){
		this.dir=dirResults;
		this.fileInputs=fileInputs;
		this.ws=ws;
	}
	
	public void getFile(String host, String fileName)
    {
        InputStream input = null;
        FileOutputStream writeFile = null;

        try
        {
            URL url = new URL(host);
            URLConnection connection = url.openConnection();
            int fileLength = connection.getContentLength();

            if (fileLength == -1)
            {
                System.out.println("Invalide URL or file.");
                return;
            }

            input = connection.getInputStream();    
            writeFile = new FileOutputStream(dir+fileName);
            byte[] buffer = new byte[1024];
            int read;

            while ((read = input.read(buffer)) > 0)
                writeFile.write(buffer, 0, read);
            writeFile.flush();
        }
        catch (IOException e)
        {
            System.out.println("Error while trying to download the file.");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                writeFile.close();
                input.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
	
	
    public void readLineByLineTheInputs() throws Exception{
    
    		BufferedReader br = new BufferedReader(new FileReader(fileInputs));
    		String line;
    		while ((line = br.readLine()) != null) {
    			// process the line.
    			System.out.println("Inputs: "+line);
    		}
    		br.close();
    	}

    public void executeCallsForInputList() throws Exception{
	    
 		BufferedReader br = new BufferedReader(new FileReader(fileInputs));
 		String line;
 		while ((line = br.readLine()) != null) {
 			
 			String input=line.trim();
 			input=input.replaceAll("\\s+","+");
 			String url=ws.getURLForInput(input);
 			System.out.println("Execute call: "+url);
 			getFile(url, input);
 			 Thread.sleep(1000);
 		}
 		br.close();
 	}
    
    public static void main(String[] args) throws Exception
    {  
    	    StubForWebServiceMethod ws=new StubForWebServiceMethod("http://musicbrainz.org/ws/2/artist/?query=", "");
    		Download download= new Download(ws, Constants.fileWithInputsForCalls,Constants.pathToCallResults);
        download.executeCallsForInputList();
    }
}
